<template>
  <div class="bank-information information-container">
    <div class="title">
      *Bank Information
    </div>

    <a-modal
      :visible="false"
    >
      <!-- <div class="institutions-container">
        <div
          class="institution-container"
          v-for="item in institutions"
          :key="item.id"
        >
          <img class="img" :src="item.logo.links.full" alt="">
          <div class="name">{{ item.shortName }}</div>
        </div>
      </div> -->

      <!-- <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
        <a-form-item label="loginId">
          <a-input
            v-decorator="['note', { rules: [{ required: true, message: 'Please input your note!' }] }]"
          />
        </a-form-item>

        <a-form-item label="password">
          <a-input
            v-decorator="['note', { rules: [{ required: true, message: 'Please input your note!' }] }]"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
          <a-button type="primary" html-type="submit">
            Submit
          </a-button>
        </a-form-item>
      </a-form> -->
      <!-- basiqConnections -->
    </a-modal>

    <!-- <a-modal
      :title="basiqConnectModal.title"
      :visible="basiqConnectModal.visible"
      @ok="basiqConnectModal.visible = false"
      @cancel="basiqConnectModal.visible = false"
      v-bind="modalProps"
    >
      <BasiqConnectModal
        v-if="isBasiq"
        :userID="basiqConnectModal.userID"
        :token="basiqConnectModal.token"
      />

      <div v-else id="basiq-control" style="min-height: 100px">loading...</div>
    </a-modal> -->

    <Promised :promise="basiqAccountsAsync">
      <template v-slot:pending>
        <a-skeleton
          :paragraph="{
            rows: 2
          }"
          active
        />
      </template>
      <template v-slot>
        <section>
          <div
            v-if="hasAccounts"
            class="infos-account-container"
          >
            <div class="banks-container">
              <div class="title">
                Authorized bank:
              </div>
              <div
                v-for="item in shortNames"
                :key="item.id"
                class="account-infos-container"
                :title="item.accountInstitution.shortName"
              >
                <img
                  class="img"
                  :src="item.accountInstitution.logo.links.full"
                  alt=""
                >
              </div>
            </div>
          </div>
          <!-- <div >
            Authorized
          </div> -->
          <a-button
            type="link"
            class="authorized-button"
            @click="basiqConnect"
          >
            Authorized Bank Card Information
          </a-button>
        </section>
      </template>
      <template v-slot:rejected="error">
        <p>Error: {{ error }}</p>
      </template>
    </Promised>
  </div>
</template>

<script>
// import { BasiqConnectModal } from '@/utils/BasiqConnectUI';
import { getBasiqAccounts, getBasiqUser, getBasiqInstitutions } from '@/api/risk/basiq';
import { mapGetters, mapState } from 'vuex';
import _ from 'lodash';

export default {
  // mixins: [basiq],

  data() {
    return {
      form: this.$form.createForm(this, { name: 'coordinated' }),

      basiqConnectModal: {
        visible: false,
        title: 'Bank authorization',
        token: '',
        userID: ''
      },

      // 机构列表
      institutions: [],

      // 账户
      accounts: [],

      basiqAccountsAsync: null,
       // props
      modalProps: {
        okButtonProps: {
          props: {
            shape: 'round'
          }
        },
        cancelButtonProps: {
          props: {
            shape: 'round'
          }
        }
      },
      loading: false
    };
  },

  computed: {
    ...mapGetters(['authentication', 'currentUser']),

    ...mapState({
      hasMobile: (state) => !!state.user.info.mobile
    }),

    hasAccounts() {
      return (this.accounts.length > 0);
    },

    shortNames() {
      return _.uniqBy(this.accounts, 'accountInstitution.shortName');
    },

    isBasiq() {
      return (this.basiqConnectModal.token && this.basiqConnectModal.userID);
    }
  },

  created() {
    this.basiqAccountsAsync = this.getBasiqAccounts();
  },

  methods: {
    // getBasiqUser
    getBasiqUser() {
      return new Promise((resolve, reject) => {
        const {
          email,
          mobile,
          first_name: firstName,
          last_name: lastName
        } = this.currentUser;
        const data = {
          email,
          mobile: `+61${mobile}`,
          firstName,
          lastName
        };
        if (!this.hasMobile) {
          resolve();
          return false;
        }
        getBasiqUser(data)
          .then(() => {
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // fill institution
    fillInstitution(id) {
      const findIndex = this.institutions
        .findIndex((item) => item.id === id);

      return findIndex > -1
        ? this.institutions[0]
        : {
          shortName: 'unknown'
        };
    },

    createAccountInstitution() {
      this.accounts.forEach((item) => {
        item.accountInstitution = this.fillInstitution(item.institution);
      });
    },

    getBasiqAccounts() {
      return new Promise((resolve, reject) => {
        this.getBasiqInstitutions()
          .then(() => {
             this.getBasiqUser()
            .then(() => {
              getBasiqAccounts()
                .then((res) => {
                  this.accounts = res.data;
                  this.createAccountInstitution();
                  resolve(res);
                })
                .catch((error) => {
                  reject(error);
                });
            })
            .catch((error) => {
              reject(error);
            });
          })
        .catch((error) => {
          reject(error);
        });
      });
    },

    // getBasiqInstitutions
    getBasiqInstitutions() {
      return new Promise((resolve, reject) => {
        this.getBasiqUser()
          .then(() => {
            getBasiqInstitutions()
              .then((res) => {
                this.institutions = res.data;
                resolve(res);
              })
              .catch(((error) => {
                reject(error);
              }));
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // basiq connect
    basiqConnect() {
      if (!this.hasMobile) {
        this.$notification.error({
          message: 'Please improve the mobile Phone Number information!',
          duration: 1
        });

        return;
      }

      this.$router.push({
        name: 'BasicSettingsAuthorize'
      });

      // this.loading = true;
      // try {
      //   // this.basiqConnectCheck()
      //   const user = await getBasiqUser();
      //   const token = await getBasiqToken();

      //   this.basiqConnectModal.userID = user.id;
      //   this.basiqConnectModal.token = token.access_token;
      //   this.basiqConnectModal.visible = true;
      //   this.loading = false;
      // } catch (error) {
      //   console.log(error);
      //   this.loading = false;
      // }
      // this.basiqConnectModal.visible = true;
    },

    // basiqConnect rule
    basiqConnectCheck() {
      if (!this.authentication) {
        this.$confirm({
          title: 'Tips',
          content: 'You need to complete your personal information and bank account information to get your loan limit!',
          cancelText: 'Cancel',
          okText: 'To perfect',
          ...this.modalProps
        });

        throw new Error();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.bank-information {
  & > .title {
    margin-bottom: $margin-xs;
  }
  .infos-account-container {
    padding-left: $padding-lg;

    .banks-container {
      display: flex;
      flex-wrap: wrap;

      & > .title {
        line-height: 55px;
        font-weight: bold;
      }
      .account-infos-container {
        width: 50px;
        height: 50px;
        border: 1px $gray-10 solid;
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: center;
        margin: 5px;

        .img {
          width: 40px;
        }
      }
    }

    // .institution-container {

    //   }
    // .account-infos-container {
    //   color: $gray-12;
    //   margin-top: $margin-sm;
    //   .value {
    //     margin-left: $margin-base;
    //     color: $black-1;
    //   }
    // }
  }

  .authorized-button {
    margin-left: $margin-md;
    font-weight: bold;
    margin-top: $margin-xs;
  }
}

.institutions-container {
  display: flex;
  flex-wrap: wrap;
  .institution-container{
    margin: $margin-sm;
    .img {
      width: 60px;
    }
  }
}
</style>
